package com.villaday.idf.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.ResidentAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.model3.GuestPostEntity;
import com.villaday.idf.model3.MemberGuestChangeEntity;
import com.villaday.idf.model3.MemberGuestEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 选择入住人
 */
public class ResidentActivity extends BaseActivity {


    @BindView(R.id.toolbar_back)
    ImageButton toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_next)
    TextView toolbarNext;
    @BindView(R.id.Line_view)
    View LineView;
    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.tv_add_rd)
    TextView tvAddRd;
    @BindView(R.id.ll_add_rd)
    LinearLayout llAddRd;
    @BindView(R.id.et_ri)
    EditText etRi;

    @BindView(R.id.tv_ri_quit)
    TextView tvRiQuit;
    @BindView(R.id.tv_ri_confirm)
    TextView tvRiConfirm;
    @BindView(R.id.rv_rd)
    RecyclerView rvRd;
    @BindView(R.id.tv_rd_confirm)
    TextView tvRdConfirm;
    @BindView(R.id.ll_resident_add)
    LinearLayout llResidentAdd;
    @BindView(R.id.et_ri_en_family)
    EditText etRiEnFamily;
    @BindView(R.id.et_ri_en_give)
    EditText etRiEnGive;


    private ResidentAdapter residentAdapter;
    private List<MemberGuestEntity.BodyBean> body;

    private MemberGuestEntity memberGuestEntity;
    private int homeNum;


    @Override
    protected int getViewResId() {
        return R.layout.activity_resident;
    }


    @Override
    protected void init() {
        super.init();
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        StatusBarUtil.setLightMode(this);
        ToolBarUtil.initToolBar(toolbarText, "选择入住人", new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //列表
        initRecycle();
        toolbarText.setBackgroundResource(R.color.colorBackground);
        Bundle bundle = getIntent().getExtras();
        homeNum = bundle.getInt("HomeNum");

        if (!bundle.getString("data").equals("default")) {
            memberGuestEntity = new Gson().fromJson(bundle.getString("data"), MemberGuestEntity.class);
            body = memberGuestEntity.getBody();
            residentAdapter.setData(body);
        } else {
            //得到客户
            getGuest();
        }

    }

    private void postGuest() {
        if (etRi.getText().length() == 0 && etRiEnGive.getText().length() == 0 && etRiEnFamily.getText().length() == 0) {
            ToastUtil.initToast(this, "中文姓名和英文姓名不能同时为空");
            return;
        }

        GuestPostEntity guestPostEntity = new GuestPostEntity();

        if (etRi.getText().length() != 0) {
            guestPostEntity.setNameCn(etRi.getText().toString());
        }
        guestPostEntity.setAction(0);
        guestPostEntity.setActionType(1);
        if (etRiEnFamily.getText().length() != 0) {
            guestPostEntity.setFamilyNameEn(etRiEnFamily.getText().toString());
        }
        if (etRiEnGive.getText().length() != 0) {
            guestPostEntity.setGivenNameEn(etRiEnGive.getText().toString());
        }
        guestPostEntity.setMobile("");
        guestPostEntity.setEmail("");
        guestPostEntity.setIdcard("");
        guestPostEntity.setPassport("");
        guestPostEntity.setPreferred(true);
        LogUtil.jLog().e(new Gson().toJson(guestPostEntity));
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.memberGuest, guestPostEntity, map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                LogUtil.jLog().e(json);
                if (!TextUtils.isEmpty(json)) {
                    MemberGuestChangeEntity memberGuestChangeEntity = new Gson().fromJson(json, MemberGuestChangeEntity.class);
                    if (memberGuestChangeEntity.getCode().equals(Constant.Strings.SUC) && memberGuestChangeEntity.getBody().getStatus() == 1) {
                        getGuest1();
                        MemberGuestEntity.BodyBean bodyBean = new MemberGuestEntity.BodyBean();
                        bodyBean.setNameCn(etRi.getText().toString());
                        bodyBean.setFamilyNameEn(etRiEnFamily.getText().toString());
                        bodyBean.setGivenNameEn(etRiEnGive.getText().toString());
                        bodyBean.setPreferred(true);
                        body.add(bodyBean);
                        if (homeNum == 1) {
                            //防止第二次进来选中两个
                            for (int i = 0; i < body.size() - 1; i++) {
                                body.get(i).setPreferred(false);
                            }
                            memberGuestEntity.setBody(body);
                            //再把bundle中的数据传给intent，以传输过去
                            Intent intent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putString("data", new Gson().toJson(memberGuestEntity));
                            intent.putExtra("bundle", bundle);
                            setResult(RESULT_OK, intent);
                            finish();
                        } else {
                            llAddRd.setVisibility(View.VISIBLE);
                            llResidentAdd.setVisibility(View.GONE);
                        }
                    } else {
                        ToastUtil.initToast(getApplicationContext(), memberGuestChangeEntity.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    /**
     * 得到用户
     */
    private void getGuest1() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, Constant.URL.memberGuest, map, new OkHttpUtil.OnDataListener() {

            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }

    /**
     * 得到用户
     */
    private void getGuest() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, Constant.URL.memberGuest, map, new OkHttpUtil.OnDataListener() {

            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    memberGuestEntity = new Gson().fromJson(json, MemberGuestEntity.class);
                    if (memberGuestEntity.getCode().equals(Constant.Strings.SUC)) {
                        body = memberGuestEntity.getBody();
                        for (int i = 0; i < body.size(); i++) {
                            body.get(i).setDeleted(false);
                            body.get(i).setPreferred(false);
                        }
                        residentAdapter.setData(body);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }

    /**
     * 初始化列表
     */
    private void initRecycle() {
        rvRd.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        residentAdapter = new ResidentAdapter(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        rvRd.setAdapter(residentAdapter);


        residentAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                int num = 0;
                for (int i = 0; i < body.size(); i++) {
                    if (body.get(i).isPreferred()) {
                        num++;
                    }
                }

                for (int i = 0; i < body.size(); i++) {
                    if (i == position) {
                        if (body.get(i).isPreferred()) {
                            num--;
                            body.get(i).setPreferred(false);
                        } else {
                            if (num < homeNum) {
                                num++;
                                body.get(i).setPreferred(true);
                            } else {
                                ToastUtil.initToast(getApplicationContext(), "只需要选择" + homeNum + "个入住人");
                            }
                        }
                    }
                }
                residentAdapter.setData(body);

                GuestPostEntity guestPostEntity = new GuestPostEntity();
                guestPostEntity.setId(body.get(position).getId());
                guestPostEntity.setNameCn(body.get(position).getNameCn());
                guestPostEntity.setAction(0);
                guestPostEntity.setActionType(1);
                guestPostEntity.setFamilyNameEn(body.get(position).getFamilyNameEn());
                guestPostEntity.setGivenNameEn(body.get(position).getGivenNameEn());
                guestPostEntity.setMobile(body.get(position).getMobile());
                guestPostEntity.setEmail(body.get(position).getEmail());
                guestPostEntity.setIdcard(body.get(position).getIdcard());
                guestPostEntity.setPassport(body.get(position).getIdcard());
                guestPostEntity.setPreferred(body.get(position).isPreferred());
                LogUtil.jLog().e(new Gson().toJson(guestPostEntity));
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(ResidentActivity.this, Constant.URL.memberGuest, guestPostEntity, map, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        LogUtil.jLog().e(json);
                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });

            }
        });
    }


    @OnClick({R.id.tv_rd_confirm, R.id.ll_add_rd, R.id.tv_ri_quit, R.id.tv_ri_confirm})
    public void btnOnclick(View view) {
        switch (view.getId()) {
            case R.id.tv_rd_confirm://确定
                memberGuestEntity.setBody(body);
                //再把bundle中的数据传给intent，以传输过去
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("data", new Gson().toJson(memberGuestEntity));
                intent.putExtra("bundle", bundle);
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.ll_add_rd:
                llAddRd.setVisibility(View.GONE);
                tvRdConfirm.setVisibility(View.GONE);
                llResidentAdd.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_ri_quit:
                llAddRd.setVisibility(View.VISIBLE);
                llResidentAdd.setVisibility(View.GONE);
                tvRdConfirm.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_ri_confirm:
                postGuest();
                break;
        }
    }
}
